'''把时间戳转化为时间: 1479264792 to 2016-11-16 10:53:12'''
import base64
import hashlib
import os
import time
import zipfile

from flask import url_for


def TimeStampToTime(timestamp):
    timeStruct = time.localtime(timestamp)
    return time.strftime('%Y-%m-%d %H:%M:%S',timeStruct)
'''获取文件的大小,结果保留两位小数，单位为MB'''
def get_FileSize(filePath):
    fsize = 0
    if os.path.isdir(filePath):
        for root, dirs, files in os.walk(filePath):
            fsize += sum([os.path.getsize(os.path.join(root, name)) for name in files])
    else:
        fsize = os.path.getsize(filePath)
    fsize = fsize/float(1024*1024)
    return round(fsize,2)
'''获取文件的访问时间'''
def get_FileAccessTime(filePath):
    t = os.path.getatime(filePath)
    return TimeStampToTime(t)
'''获取文件的创建时间'''
def get_FileCreateTime(filePath):
    t = os.path.getctime(filePath)
    return TimeStampToTime(t)
'''获取文件的修改时间'''
def get_FileModifyTime(filePath):
    t = os.path.getmtime(filePath)
    return TimeStampToTime(t)

def get_file_path(root_path,file_list,dir_list):
    #获取该目录下所有的文件名称和目录名称
    dir_or_files = os.listdir(root_path)
    for dir_file in dir_or_files:
        dirs = {}
        #获取目录或者文件的路径
        dir_file_path = os.path.join(root_path,dir_file)
        dir_file_path_create = get_FileCreateTime(dir_file_path)
        dirs['fullname'] = dir_file
        dirs['url'] = dir_file_path
        dirs['download_url'] = url_for('files.down',source_dir=base64.b64encode(dir_file_path.encode("utf-8")))
        dirs['last_modify_time'] = dir_file_path_create
        dirs['filesize'] = get_FileSize(dir_file_path)
        #判断该路径为文件还是路径
        if os.path.isdir(dir_file_path):
            dirs['is_dir'] = True
            dir_list.append(dirs)
            #递归获取所有文件和目录的路径
            get_file_path(dir_file_path,file_list,dir_list)
        else:
            dirs['is_dir'] = False
            file_list.append(dirs)

def gtree_list(pathname=None):
    if os.path.exists(pathname) == False:
        return {}
    tree_list = {}
    tree_list['nodes'] = []
    if os.path.isfile(pathname):
        tree_list['text'] = os.path.basename(pathname)
        tree_list['href'] = url_for('files.down',source_dir=base64.b64encode(pathname.encode("utf-8")))
        tree_list['tags'] = ['0']
    elif os.path.isdir(pathname):
        # self.tree_list += '    |' * n + '-' * 4 + \
        #     str(self.pathname.relative_to(self.pathname.parent)) + '\\' + '\n'
        tree_list['text'] = os.path.basename(pathname)
        tree_list['href'] = url_for('files.down',source_dir=base64.b64encode(pathname.encode("utf-8")))
        tree_list['tags'] = ['{}'.format(len(os.listdir(pathname)))]
        for cp in os.listdir(pathname):
            nodes_c = gtree_list(os.path.join(pathname,cp))
            tree_list['nodes'].append(nodes_c)
    return tree_list


#打包目录为zip文件（未压缩）
def make_zip(source_dir, output_filename):
  zipf = zipfile.ZipFile(output_filename, 'w')
  pre_len = len(os.path.dirname(source_dir))
  if os.path.isdir(source_dir):
      for parent, dirnames, filenames in os.walk(source_dir):
        for filename in filenames:
          pathfile = os.path.join(parent, filename)
          arcname = pathfile[pre_len:].strip(os.path.sep)   #相对路径
          zipf.write(pathfile, arcname)
  else:
      if os.path.isfile(source_dir):
          arcname = source_dir[pre_len:].strip(os.path.sep)  # 相对路径
          zipf.write(source_dir, arcname)
  zipf.close()


#打包目录为zip文件（未压缩）
def make_zip_files(files, output_filename):
  zipf = zipfile.ZipFile(output_filename, 'w')
  for f in files:
      if os.path.isfile(f.wjccwz):
          zipf.write(f.wjccwz, f.wjm)
  zipf.close()

def readPart(filePath, size=1024, encoding="utf-8"):
    with open(filePath,"r",encoding=encoding) as f:
        while True:
            part = f.read(size)
            if part:
                yield part
            else:
                return None

def get_md5_file(f_path):
    # f_path = self.textbox.text()
    #单行文本框的内容，即文件路径
    with open(f_path, 'rb') as f:
        md5obj = hashlib.md5()
        md5obj.update(f.read(4096*4096))
        _hash = md5obj.hexdigest()
        haxi_data = str(_hash).upper()
    return haxi_data